// src/nodes/OutputNode.js
import React, { useState, useEffect } from 'react';
import { Handle } from 'reactflow';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faArrowRightFromBracket, faCopy } from '@fortawesome/free-solid-svg-icons';

const OutputNode = ({ data, id }) => {
  const [displayText, setDisplayText] = useState('');
  const [isAnimating, setIsAnimating] = useState(false);
  const [copied, setCopied] = useState(false);

  const copyNodeId = () => {
    navigator.clipboard.writeText(id)
      .catch(err => console.error('Failed to copy:', err));
  };

  // 复制输出内容
  const handleCopy = () => {
    navigator.clipboard.writeText(displayText)
      .then(() => {
        setCopied(true);
        setTimeout(() => setCopied(false), 2000);
      })
      .catch(err => console.error('复制失败:', err));
  };

  useEffect(() => {
    const getNestedValue = (obj, path) => {
      if (!path) return undefined;
      // 将方括号索引语法转换为点表示法（如"skills[0]"→"skills.0"）
      const normalizedPath = path.replace(/\[(\d+)\]/g, '.$1');
      return normalizedPath.split('.').reduce((acc, part) => {
        if (acc === null || acc === undefined || typeof acc !== 'object') return undefined;
        
        // 判断是否为数字索引（数组访问）
        const isArrayIndex = /^\d+$/.test(part);
        if (isArrayIndex) {
          const index = parseInt(part, 10);
          return Array.isArray(acc) && index < acc.length ? acc[index] : undefined;
        } else {
          return acc[part]; // 普通对象属性访问
        }
      }, obj);
    };
  
    if (data.input_data) {
      setIsAnimating(true);
      let parsedData;
      let displayContent;
      
      try {
        if (typeof data.input_data === 'object') {
          parsedData = data.input_data;
          if (data.selectedVariable) {
            const value = getNestedValue(parsedData, data.selectedVariable);
            
            displayContent = value !== undefined 
              ? typeof value === 'object' 
                ? JSON.stringify(value, null, 2)  // 格式化对象/数组
                : value.toString()                 // 基本类型转字符串
              : `Variable "${data.selectedVariable}" not found`;
          } else {
            displayContent = JSON.stringify(parsedData, null, 2);
          }
        } else {
          displayContent = data.input_data;
        }
      } catch (e) {
        console.log('parsedData error: ', e);
        displayContent = data.input_data;
      }

      data.content = displayContent;
  
      // 打字机动画效果
      let currentIndex = 0;
      const typingEffect = setInterval(() => {
        setDisplayText(prev => displayContent.slice(0, currentIndex));
        currentIndex++;
        if (currentIndex > displayContent.length) {
          clearInterval(typingEffect);
          setIsAnimating(false);
        }
      }, 30);
  
      return () => clearInterval(typingEffect);
    }
  }, [data.input_data, data.selectedVariable, data]);

  return (
    <div className="bg-blue-50 p-5 rounded-lg shadow-md w-80 relative transition-all duration-200 hover:shadow-lg"
    >
      <div className="flex items-center mb-4">
        <FontAwesomeIcon 
          icon={faArrowRightFromBracket} 
          className={`mr-2 text-gray-600 text-sm ${
                isAnimating ? 'bg-green-500 animate-pulse' : ''
            }`} 
        />
        <h3 className="text-sm font-semibold text-gray-800 tracking-wide">输出节点</h3>
      </div>

      <div className="flex items-center gap-1 text-xs text-gray-500 mt-1 mb-2">
        <p className="overflow-hidden truncate">nodeID: {id}</p>
        <FontAwesomeIcon 
          icon={faCopy}
          className="text-gray-400 hover:text-blue-500 cursor-pointer ml-1"
          onClick={(e) => {
            e.stopPropagation();
            copyNodeId();
          }}
          title="复制节点ID"
        />
      </div>

      <input
        value={data.selectedVariable || ''}
        onChange={(e) => data.onVariableChange(e.target.value)}
        placeholder="输入变量名（如：name）"
        className="w-full px-3 py-2 mb-4 text-xs rounded-md border border-gray-300 
                 focus:outline-none focus:ring-2 focus:ring-green-200 focus:border-green-500
                 transition-all placeholder:text-gray-400"
      />

      <div className="bg-white rounded-md p-4 h-[100px] border border-gray-200 relative
                    transition-colors duration-200 hover:border-gray-300 overflow-y-auto">
        {displayText ? (
          <>
            <pre className="text-xs text-gray-700 leading-relaxed font-mono 
                          whitespace-pre-wrap break-words m-0 max-w-full overflow-x-hidden">
              {displayText}
            </pre>
            <div className="absolute right-2 top-1.5 text-[10px] text-gray-500 font-medium flex items-center gap-1">
              {isAnimating ? (
                <span className="flex items-center">
                  <span className="mr-1">处理中</span>
                  <span className="loading-dots">
                    <span>.</span><span>.</span><span>.</span>
                  </span>
                </span>
              ) : (
                <>
                  <span>✅ 完成</span>
                  <button 
                    onClick={handleCopy} 
                    className="hover:text-gray-700 transition-colors"
                    title="复制输出"
                  >
                    <FontAwesomeIcon icon={faCopy} className="ml-1" />
                  </button>
                  {copied && <span className="text-green-500">已复制!</span>}
                </>
              )}
            </div>
          </>
        ) : (
          <div className="absolute inset-0 flex items-center justify-center text-gray-400 text-xs">
            <span className="animate-fade-in">等待输入数据...</span>
          </div>
        )}
      </div>

      <Handle
        id="input"
        type="target"
        position="left"
        className="!w-4 !h-4 !bg-green-500 !border-white"
      />
      {data.out_handle === 'yes' && (
        <Handle
          id="output"
          type="source"
          position="right"
          className="!w-4 !h-4 !bg-blue-500 !border-white"
        />
      )}

    </div>
  );
};

export default OutputNode;